import os
import requests
import logging
from celery import shared_task
from django.conf import settings



logger = logging.getLogger(__name__)


@shared_task
def update_cwe_json():
    """
    Download the latest CWE JSON file from the APTRS-CWE repository.
    Repo is updated every week with updated CWE JSON
    """
    cwe_url = "https://raw.githubusercontent.com/APTRS/APTRS-CWE/main/cwe.json"
    base_dir = settings.BASE_DIR
    data_dir = os.path.join(base_dir, "data")
    os.makedirs(data_dir, exist_ok=True)

    cwe_file_path = os.path.join(data_dir, "cwe.json")

    try:
        # Download the JSON file
        logger.info("Starting download of CWE JSON data.")
        response = requests.get(cwe_url, timeout=10)
        response.raise_for_status()

        # Save it to the data directory
        with open(cwe_file_path, 'w') as file:
            file.write(response.text)

        logger.info(f"CWE JSON updated successfully at {cwe_file_path}")
    except requests.RequestException as e:
        logger.error(f"Error updating CWE JSON: {e}")